<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/10/30
 * Time: 上午11:06
 */

namespace app\index\controller;


use think\captcha\Captcha;
use think\Controller;
use think\Db;

class Log   extends Controller
{
    protected $weibo = [
        'client_id' => '3002858390',
        'secret' => 'dcbf3f03a71d0e86efcfff92b4ee8aca',
        'redirect_uri'=>'http://yyw.weiyinstudio.com/'
    ];

    public function login ()
    {

        // 判断是否通过推荐过来的会员
        $pid = input('get.id' , '' , 'htmlspecialchars');
        $key = input('get.key' , '','htmlspecialchars');

        if ($pid!='' && md5($pid . '3edtrjhkop90878yghvnmkljjhgcfyuy') == $key) {
            session('pid' , $pid);
        }else if ($pid !='' && md5($pid . '3edtrjhkop90878yghvnmkljjhgcfyuy') != $key) {
            $this->error('非法url' , 'index/index');
            die;
        }

        // 微博登录url
        $weibo = 'https://api.weibo.com/oauth2/authorize?client_id='.$this->weibo['client_id'].'&response_type=code&redirect_uri='.$this->weibo['redirect_uri'].'?backurl=http://www.1808yysh.com/index.php/index/log/weibo';
        $this->assign('weibo' , $weibo);
        return view();
    }

    public function checklogin ()
    {
            $post = input('post.' , '' , 'htmlspecialchars');
            $username = $post['username'];
            $phone = $post['username'];
            $post['password'] = md5($post['password']);
            $captcha = $post['captcha'];
//             验证验证码是否正确
            if(!captcha_check($captcha)){
                $this->error('验证码错误');
                die;
            };
            unset($post['captcha']);
            $info = db('member')->whereOr('username' , $username)->whereOr('phone' , $phone)->where('password' , $post['password'])->find();
            $GLOBALS['info'] = $info;
            if (!empty($info)) {
                if ($info['pid'] == 0 && session('pid') != null) {
                    // 代表这个用户虽然有注册过账号，但是没有上级
                    db('member')->where('id' , $info['id'])->update(['pid'=> session('pid')]);

                    Db::transaction(function() {

                        // 发放推荐奖
                        $member = model('member');
                        // 一级推荐人
                        $info = $GLOBALS['info'];

                        $referee1 = $member->getReferee($info['id']);
                        // 二级推荐人
                        $referee2 = $member->getReferee($referee1['id']);
                        if (!empty($referee2)) {
                            // 三级推荐人
                            $referee3 = $member->getReferee($referee2['id']);
                        }
                        $point1 = db('config')->where('name' , '一级推荐奖励')->find();
                        $point2 = db('config')->where('name' , '二级推荐奖励')->find();
                        $point3 = db('config')->where('name' , '三级推荐奖励')->find();

                    db('accessLog')->insert(['msg'=>'成功推荐'.$info['username'].';获得一级推荐奖励'.$point1['value'], 'to_user'=>$referee1['id'] , 'type'=>1 , 'addtime'=>time()]);
                    db('member')->where('id' , $referee1['id'])->setInc('point' , $point1['value']);
                    if (!empty($referee2)) {
                        db('accessLog')->insert(['msg' => '成功推荐' . $info['username'] . ';获得二级推荐奖励' . $point2['value'], 'to_user' => $referee2['id'], 'type' => 1, 'addtime' => time()]);
                        db('member')->where('id', $referee2['id'])->setInc('point', $point2['value']);
                        if (isset($referee3) && !empty($referee3)) {
                            db('accessLog')->insert(['msg'=>'成功推荐'.$info['username'].';获得三级推荐奖励'.$point3['value'], 'to_user'=>$referee3['id'] , 'type'=>1 , 'addtime'=>time()]);
                            db('member')->where('id' , $referee3['id'])->setInc('point' , $point3['value']);
                        }
                    }


                    });
                }
                session('id' , $info['id']);
                session('username' , $info['username']);
                session('nickname' , $info['nickname']);
                $this->success('登录成功' , url('user/user'));
            }else {
                $this->success('用户名或密码错误');
            }

    }

    public function reg ()
    {
        return view();
    }

    public function captcha ()
    {

        $config = [
//            'useZh' => true,
//            'fontttf'=> realpath('/static/a.ttc'),
//            'useImgBg'=>true,
            'length' => 2,
            'useCurve'=>false,
            'useNoise'=>false
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }


    public function logout ()
    {
        session('id' , null);
        session('username' , null);
        session('nickname' , null);
        $this->success('退出成功' , 'login');
    }

    public function weibo ()
    {
        $code = input('get.code');
        $url = 'https://api.weibo.com/oauth2/access_token?client_id='.$this->weibo['client_id'].'&client_secret='.$this->weibo['secret'].'&grant_type=authorization_code&redirect_uri='.$this->weibo['redirect_uri'].'&code='.$code;
        $content = curl($url , []);
        $access_token = json_decode($content , true);

        $url = 'https://api.weibo.com/2/users/show.json?access_token='.$access_token['access_token'].'&uid='.$access_token['uid'];
        $info = curl($url);
        $info = json_decode($info , true);

        $has = db('member')->where('weibo_id' , $info['id'])->find();
        if (!$has) {
            $insert_data = [
                'nickname' => $info['name'],
                'header_img'=>$info['profile_image_url'],
                'weibo_id' => $info['id']
            ];
            $id = db('member')->insertGetId($insert_data);

        }else {
            $update_data = [
                'nickname' => $info['name'],
                'header_img'=>$info['profile_image_url'],
            ];
            $where = [
                'weibo_id' => $info['id']
            ];
            $id = $has['id'];
            db('member')->where($where)->update($update_data);
        }
        $info = db('member')->where('weibo_id' , $info['id'])->find();

        if ($id) {
            session('id' , $id);
            session('nickname' , $info['name']);
            if(!$info['phone']) {
                $this->redirect('bind');
            }
            $this->success('登录成功' , 'user/user');
        }else {
            $this->error('登录失败' , 'log/login' );
        }
    }

    public function bind () {
        return view();
    }

    public function bindPhone () {
        $post = input('post.');
        if (session('phone') == $post['phone'] && session('phoneCode') == $post['phonecode']) {
            db('member')->where('id' , session('id'))->update(['phone' => $post['phone']]);
            $this->success('绑定成功' , 'user/user');
        }else {
            $this->error('绑定失败!');
        }
    }

    public function checkPhoneCode () {
        $post = input('post.');
        $captcha = $post['captcha'];
        if(!captcha_check($captcha)){
            $this->error('验证码错误');
            die;
        };
        $phoneCode = mt_rand(1000 , 9999);
        session('phone' , $post['phone']);
        session('phoneCode' , $phoneCode );
        $url = 'http://v.juhe.cn/sms/send';
        $data = [
            'mobile' => $post['phone'],
            'tpl_id'=> '110838',
            'tpl_value'=> urlencode('#code#='.$phoneCode),
            'key'=> '2f524705d0380ff37b64dda6fe032266',
        ];
        echo curl($url , $data);

    }
}